<?php

namespace App\Http\Controllers\Dashboard;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class LoginController extends BaseController
{
    const TOKEN_APP = 'dashboard';
    /**
     * 密码登录
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request) {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'password' => 'required',
        ], [
            'required' => ':attribute 必填',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $user = User::where('mobile', $request->mobile)->first();
        if (empty($user)) {
            return response()->json([
                'msg' => "用户不存在",
                'code' => 500,
                'data' => null,
            ]);
        }

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'code' => 1,
                'msg' => '帐号或密码不正确'
            ]);
        } else if (empty($user->org_code)) {
            return response()->json([
                'msg' => "未开通系统登录权限",
                'code' => 500,
            ]);
        } else if ($user->status != 1) {
            return response()->json([
                'msg' => "当前用户状态不能登录",
                'code' => 500,
            ]);
        } else {
            if (config('app.env') !== 'local') {
                $user->tokens()->where('name', self::TOKEN_APP)->delete();
            }

            return response()->json([
                'msg' => "ok",
                'code' => 0,
                'data' => [
                    'token' =>  $user->createToken(self::TOKEN_APP)->plainTextToken,
                    'uid' => $user->id,
                    'name' => $user->name,
                    'mobile' => $user->mobile,
                    'is_manager' => (bool) $user->is_manager,
                    'is_manager_root' => $user->isRootManager(),
                    'is_manager_supper' => $user->isSupper(),
                    'menu' => build_tree(getUserMenu($user))
                ],
            ]);
        }
    }

    /**
     * 使用验证码登录
     * @return JsonResponse
     */
    public function loginBySmsCode(Request $request) {

        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'sms_code' => 'required',
        ], [
            'required' => ':attribute 必填',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $user = User::where('mobile', $request->mobile)->first();
        if (empty($user)) {
            return response()->json([
                'msg' => "用户不存在",
                'code' => 500,
                'data' => null,
            ]);
        }

        $key = sprintf("sms_%s", $request->mobile);
        if (Cache::get($key) != $request->sms_code) {
            return response()->json([
                'msg' => "验证码不正确",
                'code' => 500,
                'data' => null,
            ]);
        }

        if (empty($user->org_code)) {
            return response()->json([
                'msg' => "未开通系统登录权限",
                'code' => 500,
                'data' => null,
            ]);
        } else if ($user->status != 1) {
            return response()->json([
                'msg' => "当前用户状态不能登录",
                'code' => 500,
            ]);
        }

        // 登录成功
        if (config('app.env') !== 'local') {
            $user->tokens()->where('name', self::TOKEN_APP)->delete();
        }

        return response()->json([
            'msg' => "ok",
            'code' => 0,
            'data' => [
                'token' =>  $user->createToken(self::TOKEN_APP)->plainTextToken,
                'uid' => $user->id,
                'name' => $user->name,
                'mobile' => $user->mobile,
                'is_manager' => (bool) $user->is_manager,
                'is_manager_root' => $user->isRootManager(),
                'is_manager_supper' => $user->isSupper(),
                'menu' => build_tree(getUserMenu($user))
            ],
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function sendSmsCode(Request $request) {
        if (empty($request->mobile)) {
            return response()->json([
                'msg' => "手机号码不正确",
                'code' => 500,
                'data' => null,
            ]);
        }

        $user = User::where('mobile', $request->mobile)->first();
        if (empty($user)) {
            return response()->json([
                'msg' => "用户不存在",
                'code' => 500,
                'data' => null,
            ]);
        }

        $key = sprintf("sms_%s", $request->mobile);
        $lock_key = sprintf("sms_%s_lock", $request->mobile);

        if (Cache::has($lock_key)) {
            return response()->json([
                'msg' => "请不要频繁操作",
                'code' => 500,
                'data' => null,
            ]);
        }
        $sms_code = random_int(100000, 999999);

        $status = send_sms_login($request->mobile, $sms_code);
        dd($status);
        Log::debug(sprintf("Login sms code %s : %s", $request->mobile, $sms_code));
        Cache::put($key, $sms_code, 1800);
        Cache::put($lock_key, true, 59);
        return response()->json([
            'msg' => '短信发送成功',
            'code' => 0,
            'data' => "短信发送成功",
        ]);

//        if (send_sms_login($request->mobile, $sms_code)) {
//            Log::debug(sprintf("Login sms code %s : %s", $request->mobile, $sms_code));
//            Cache::put($key, $sms_code, 1800);
//            Cache::put($lock_key, true, 59);
//            return response()->json([
//                'msg' => '短信发送成功',
//                'code' => 0,
//                'data' => "短信发送成功",
//            ]);
//        } else {
//            return response()->json([
//                'msg' => '短信发送失败',
//                'code' => 500,
//                'data' => "短信发送失败",
//            ]);
//        }
    }

    /**
     * 当前登录用户的基本信息
     *
     * @return JsonResponse
     */
    public function  whoami() {
        // 没有登录
        if (!auth('sanctum')->check()) {
            return response()->json([
                'code' => 401,
                'msg' => 'not login'
            ], 401);
        } else {
            // 获取当前用户机构号
            $user =  auth('sanctum')->user();
            // 获取用户权限菜单
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'uid' => $user->id,
                    'name' => $user->name,
                    'mobile' => $user->mobile,
                    'is_manager' =>  (bool)$user->is_manager,
                    'is_manager_root' => $user->isRootManager(),
                    'is_manager_supper' => $user->isSupper(),
                    'menu' => build_tree(getUserMenu($user))
                ]
            ]);
        }
    }

    /**
     * 退出登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function logout(Request $request) {
        $request->user()->tokens()->where('name', self::TOKEN_APP)->delete();

        return response()->json([
            'code' => 0,
            'msg' => 'ok'
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public  function resetPassword(Request $request) {
        $validator = Validator::make($request->all(), [
            'password' => 'required|min:6',
            're_password' => 'required|same:password',
        ], [
            'required' => ':attribute 必填',
            'same' => '两次密码不一致',
            'min' => '最少 :min 位密码'
        ]);
        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $user = $request->user();
        $user->password = Hash::make($request->password);
        if ($user->save()) {
            return response()->json([
                'msg' => 'ok',
                'code' => 0,
                'data' => "密码重置成功",
            ]);
        } else {
            return response()->json([
                'msg' => 'fail',
                'code' => 500,
                'data' => "密码重置识别",
            ]);
        }
    }
}
